#include "stateMachineTester.h"
#include "stdbool.h"
#define MAX_RETRY 10

bool crcChecker(void *);

bool crcChecker(void *d){
	void *tmp;
	tmp = d;
	return true;
}

StateOutcome HandshakeMachineTesterTXsentState (void* me,const Event* e){
	HandShakeMachine* temp = (HandShakeMachine*) me;
	bool control;
	switch(e->signature){

		case INIT_CODE:
			temp->retryCounter = 0;
		case ENTRY_CODE: //esegui send
			temp->timer=0; //partenza timeout
			return EVENT_HANDLED;
		case HAND_SHAKE_MACHINE_RX_EVENT_CODE:
			control=crcChecker(e->data);
			if (control)
			{
				//stoppa timeout
				temp->super.state=HandshakeMachineTesterOkState;
				return EVENT_CHANGED;
			}
			else
			{
				return EVENT_CHANGED;
			}
		case HAND_SHAKE_MACHINE_TIMEOUT_EVENT_CODE:
			if (++(temp->retryCounter) == MAX_RETRY)
			{
				temp->super.state=HandshakeMachineTesterFailState;
				return EVENT_CHANGED;
			}
			else
				return EVENT_CHANGED;
		default:
			return EVENT_IGNORED;
	}
}
StateOutcome HandshakeMachineTesterOkState (void* me,const Event* e){
	HandShakeMachine* temp=(HandShakeMachine*) me;
	switch (e->signature)
	{
	default:
		temp->okEnder(temp->notifierTarget);
	}
	return EVENT_HANDLED;
}
StateOutcome HandshakeMachineTesterFailState (void* me,const Event* e){
	HandShakeMachine* temp=(HandShakeMachine*) me;
	switch (e->signature)
	{
	default:
		temp->failEnder(temp->notifierTarget);
	}
	return EVENT_HANDLED;
}
void initTransmission(HandShakeMachine* engine, void* port, uint32_t canId, uint8_t payloadSize, uint8_t* payload, uint32_t answerId, void* notifTarget, Notifier onOk, Notifier onFail){
	int itera;
	engine->paramCheck = answerId;
	engine->canPort = port;
	engine->okEnder = onOk;
	engine->failEnder = onFail;
	engine->notifierTarget = notifTarget;

	if (payloadSize != 0){
		for (itera = 0; itera < payloadSize; itera++)
			engine->TxBuffer[itera] = payload[itera];
	}

	engine->sizeTx = payloadSize;
	engine->msgIdentifier = canId;
	//finite le inizializzazioni la trasmissione inizia
	stateMachineOnInit((void*) engine, HandshakeMachineTesterTXsentState);
}
